import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {AlertComponent, MessageService, ModalComponent} from '../../../../../ng-tools';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {TicketService} from '../../../../services/api/ticket.service';
import {HttpParams} from '@angular/common/http';
import {ActivatedRoute, Router} from '@angular/router';
import {GameTypeChooseComponent} from '../game-type-choose/game-type-choose.component';

@Component({
  selector: 'system-group-edit',
  templateUrl: './game-group-edit.component.html',
  styleUrls: ['./game-group-edit.component.scss']
})
export class GameGroupEditComponent implements OnInit, AfterViewInit {
  breadcrumb = [
    {name: '游戏群', cssIcon: 'fa fa-fw fa-gamepad', link: '/main/oplatform/game-group'},
    {name: '编辑', cssIcon: 'fa fa-fw fa-pencil-square'}
  ];
  @ViewChild('modal') private modal: ModalComponent;
  @ViewChild('fileInput') fileInput;
  @ViewChild('imageElement') imageElement;
  configForm: FormGroup;
  currentGroup;
  alterOption = {
    theme: 'success',
    data: '',
    position: 'center'
  };
  file_name = '';
  playTypeInfo = '';
  imageUrl;
  @ViewChild('alert') private alert: AlertComponent;
  @ViewChild('inputElement') inputElement;
  constructor(private formBuilder: FormBuilder,
              private router: Router,
              private message: MessageService,
              private routeInfo: ActivatedRoute,
              private ticketService: TicketService) {
    try {
      this.currentGroup = JSON.parse(this.routeInfo.queryParams['_value']['gameGroup']);
    } catch (e) {
      this.currentGroup = null;
    }
    this.configForm = this.formBuilder.group({
      g_name: ['', Validators.required],
      id: ['', ],
      announcement: ['', Validators.required],
      play_type: ['', Validators.required],
      g_img_file: ['', ],
      robot_group_id: ['', ],
      times: ['', ],
      isJoinSpecialReward: ['', ],
      low_account: ['', ],
      high_account: ['', ],
      multi: ['', ],
      sendPacketUserOfJL: ['', ],
      platFlPerc: ['', ],
      level: ['', ],
    });
  }

  ngOnInit() {
    if (this.currentGroup !== null) {
      this.configForm.patchValue({
        g_name: this.currentGroup.gName,
        announcement: this.currentGroup.announcement,
        play_type: this.currentGroup.play_type,
        id: this.currentGroup.gid,
        robot_group_id: this.currentGroup.robot_group_id
      });
      this.playTypeInfo = this.formatterGroupData(this.currentGroup.play_type, [1, 2, 3], ['扫雷群', '牛牛红包群', '红包接龙群']);
      this.imageUrl = this.ticketService.serverConfig.httpServer + this.ticketService.baseUrl + this.ticketService.urls.GroupAvatarDownloader + '?action=ad&g_id=' + this.currentGroup.gid + '&enforceDawnload=1';
      console.log(this.configForm.value);
    }
  }
  formatterGroupData(value: any, values: any[], status: any[]) {
    if (values.length !== status.length) {
      throw new Error(`values.length != colors.length`);
    }

    let result;
    for (let i = 0; i < values.length; i++) {
      if (value === values[i]) {
        result = status[i];
      }
    }
    return result;
  }
  showChooseGameType() {
    this.modal.show({
      title: '游戏配置',
      cssIcon: 'fa fa-fw fa-plus-circle',
      dynamicComponent: {
        component: GameTypeChooseComponent,
        data: this.currentGroup,
        events: {
          success: (data) => {
            this.modal.hide();
            if (this.formatterGroupData(data.play_type, [1, 2, 3], ['扫雷群', '牛牛红包群', '红包接龙群']) !== this.playTypeInfo) {
              this.playTypeInfo = this.formatterGroupData(data.play_type, [1, 2, 3], ['扫雷群', '牛牛红包群', '红包接龙群']);
            }
            this.configForm.patchValue(data);
            this.inputElement.nativeElement.value = this.playTypeInfo;
          }
        },
      },
      data: null
    });
  }
  changeAvatar() {
    this.fileInput.nativeElement.click();
  }
  selectFile(e) {
    const formData = new FormData();
    this.file_name = e.target.files[0].name;
    formData.append('file_name', e.target.files[0].name);
    formData.append('file',  e.target.files[0]);
    this.ticketService.post(this.ticketService.urls.GroupAvatarUploader, formData, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
      console.log(resp);
      if (resp.body.success) {
        this.file_name = resp.body.returnValue.groupHeadImg;
        this.configForm.patchValue({g_img_file: resp.body.returnValue.groupHeadImg});
        this.configForm.value.g_img_file = resp.body.returnValue.groupHeadImg;
          const reader = new FileReader();
          reader.readAsDataURL(e.target.files[0]);
          reader.onload = () => {
            this.imageUrl = reader.result;
            this.imageElement.nativeElement.src = this.imageUrl;
        };
      }
    });
  }
  save() {
    if (this.configForm.valid) {
      if (this.currentGroup !== null && this.currentGroup !== undefined) {
        this.configForm.value.id = this.currentGroup.gid;
      } else {
        this.configForm.value.g_img_file = this.file_name;
      }
      console.log(this.configForm.value);
      this.ticketService.post(this.ticketService.urls.createGameGroup, this.configForm.value, {
        observe: 'response',
        params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
        if (resp.body.success) {
          this.router.navigate(['main/oplatform/game-group'], ).catch();
        } else {
          this.alterOption.theme = 'danger';
          this.alterOption.data = resp.body.msg;
          this.alert.show(this.alterOption, 2000);
        }
      });
    }
  }

  ngAfterViewInit(): void {
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
  }

}
